import { View, Input, Textarea, Image, Button } from '@tarojs/components';
import { useState } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { AddressType, goToFillAddress } from '@/utils/address';
import { getUser } from '@/utils/user';

import './index.less';
import Taro from '@tarojs/taro';
import request from '@/utils/request';
import { IOrder } from '@/types/order';
import { apiDomain} from "@/constant";

// 计算价格函数
const calculatePrice = (parcelNumber: string, bigParcelNumber: string) => {
  return Number(parcelNumber) * 2 + Number(bigParcelNumber) * 5;
}

export default function Index() {
  const user = getUser();
  const { fullAddress = "" } = useSelector((state: RootState) => state.address);
  const [parcelNumber, setParcelNumber] = useState('0');
  const [bigParcelNumber, setBigParcelNumber] = useState('0');
  const [phone, setPhone] = useState(user?.phone||'');
  const [remark, setRemark] = useState('');
  const [imageList, setImageList] = useState<string[]>([]);

  const handleChooseImage = () => {
    Taro.chooseImage({
      count: 9 - imageList.length, // 最多可以选择的图片张数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        
        // 上传图片到服务器
        tempFilePaths.forEach(path => {
          uploadImage(path);
        });
      }
    });
  };

  const uploadImage = (filePath: string) => {
    // 显示上传中
    Taro.showLoading({
      title: '上传中...',
    });
    
    // 上传图片
    Taro.uploadFile({
      url: apiDomain + '/oss/upload', // 替换为你的上传接口
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': Taro.getStorageSync('token')
      },
      success: function (res) {
        Taro.hideLoading();
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          // 上传成功，更新图片列表
          setImageList(prev => [...prev, data.data.url]);
        } else {
          Taro.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: function () {
        Taro.hideLoading();
        Taro.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        });
      }
    });
  };

  const removeImage = (index: number) => {
    const newList = [...imageList];
    newList.splice(index, 1);
    setImageList(newList);
  };

  const handlePublish = () => {
    // 处理发布逻辑

    if(parcelNumber === '0' && bigParcelNumber === '0'){
      Taro.showToast({
        title: '请设置小件数量和大件数量',
        icon: 'none',
      });
      return;
    }

    if(fullAddress?.length <= 5){
      Taro.showToast({
        title: '请设置居住地址',
        icon: 'none',
      });
      return;
    }

    // 验证取件码和快递照片至少填写一项
    if(!remark.trim() && imageList.length === 0) {
      Taro.showToast({
        title: '请填写取件码或上传快递照片',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    const createOrder = async () => {
      const orderAmount = calculatePrice(parcelNumber, bigParcelNumber);
      const order = await request.post<IOrder>('/order/create', {
        orderAmount: orderAmount,
        userId: user?.id,
        orderType: "parcel",
        desc: remark,
        takeNum: parcelNumber,
        takeBigNum: bigParcelNumber,
        fullAddress: fullAddress,
        phone: phone,
        imageList: imageList,
      });
      console.log("order",order);
      if(order?.id){
        // 跳转到order-review页面
        Taro.navigateTo({
          url: `/pages/order-review/index?price=${orderAmount}&orderId=${order?.id}`,
        });
      }
    }
    createOrder();
  };

  const handleNumberChange = (type: 'parcel' | 'bigParcel', operation: 'add' | 'minus') => {
    if (type === 'parcel') {
      const currentNum = parseInt(parcelNumber);
      if (operation === 'add') {
        setParcelNumber((currentNum + 1).toString());
      } else if (operation === 'minus' && currentNum > 0) {
        setParcelNumber((currentNum - 1).toString());
      }
    } else {
      const currentNum = parseInt(bigParcelNumber);
      if (operation === 'add') {
        setBigParcelNumber((currentNum + 1).toString());
      } else if (operation === 'minus' && currentNum > 0) {
        setBigParcelNumber((currentNum - 1).toString());
      }
    }
  };

  return (
    <View className="take-parcel">
      <View className="content">
        {/* <Image 
          className="banner"
          src="https://your-image-url.com/rules.png" // 需要替换为实际的图片地址
          mode="widthFix"
        /> */}
        <View className="form">
          <View className="form-item">
            <View className="label">取件日期：24小时内</View>
          </View>
          <View className="form-item">
            <View className="label">小件数量</View>
            <View className="number-input-wrapper">
              <View 
                className="btn-number minus" 
                onClick={() => handleNumberChange('parcel', 'minus')}
              >-</View>
              <Input 
                className="input number-input"
                type="number"
                value={parcelNumber}
                disabled
                placeholder="快递数量"
                placeholderClass="placeholder"
              />
              <View 
                className="btn-number plus" 
                onClick={() => handleNumberChange('parcel', 'add')}
              >+</View>
            </View>
          </View>
          <View className="form-item">
            <View className="label">大件数量</View>
            <View className="number-input-wrapper">
              <View 
                className="btn-number minus" 
                onClick={() => handleNumberChange('bigParcel', 'minus')}
              >-</View>
              <Input 
                className="input number-input"
                type="number"
                value={bigParcelNumber}
                disabled
                placeholder="大件数量"
                placeholderClass="placeholder"
              />
              <View 
                className="btn-number plus" 
                onClick={() => handleNumberChange('bigParcel', 'add')}
              >+</View>
            </View>
          </View>

          <View className="form-item">
            <View className="label">价格：<View className="price">{calculatePrice(parcelNumber, bigParcelNumber)} 元</View></View>
          </View>

          <View className="form-item">
            <View className="label">居住地址</View>
            <View className="address-wrapper">
              <Input 
                className="input"
                type="text"
                value={fullAddress}
                disabled
                placeholder="请先设置您的居住地址"
                placeholderClass="placeholder"
              />
              <Button 
                className="btn-edit-address" 
                onClick={()=>{
                  goToFillAddress(AddressType.BACK);
                }}
              >
                修改
              </Button>
            </View>
            <View className="tip">手动修改住址变更可至「我的-居住地址」中更新</View>
          </View>

          <View className="form-item">
            <View className="label">手机号</View>
            <Input 
              className="input"
              type="number"
              value={phone}
              onInput={e => setPhone(e.detail.value)}
              placeholder="请输入您的手机号"
              placeholderClass="placeholder"
            />
          </View>

          <View className="form-item">
            <View className="label">取件码</View>
            <Textarea
              className="textarea"
              value={remark}
              onInput={e => setRemark(e.detail.value)}
              placeholder="请填写取件码（与照片至少选填一项）"
              placeholderClass="placeholder"
            />
          </View>
          
          <View className="form-item">
            <View className="label">上传快递照片</View>
            <View className="image-upload-area">
              {imageList.map((image, index) => (
                <View className="image-item" key={index}>
                  <Image src={image} className="preview-image" mode="aspectFill" />
                  <View className="remove-icon" onClick={() => removeImage(index)}>×</View>
                </View>
              ))}
              
              {imageList.length < 9 && (
                <View className="upload-button" onClick={handleChooseImage}>
                  <View className="plus-icon">+</View>
                  <View className="upload-text">添加图片</View>
                </View>
              )}
            </View>
            <View className="tip">取件码和照片至少填写一项，最多可上传9张图片</View>
          </View>
        </View>
      </View>

      <View className="footer">
        <Button 
          className="btn btn-publish" 
          onClick={handlePublish}
        >
          <View className="button-content">
            <View className="text">发布</View>
          </View>
        </Button>
      </View>

    </View>
  );
}
